﻿using System;
using System.Collections.Generic;
using System.Linq;
using DotNetNuke.Web.Services;
using DotNetNuke.Entities.Users;
using DotNetNuke.Modules.DNNFiddle.Data;
using DotNetNuke.Security;
using System.Web.Mvc;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Common;
using System.IO;

namespace DotNetNuke.Modules.DNNFiddle.Services
{
    [SupportedModules("DNNFiddle")]
    public class FiddleController: DnnController
    {
        [HttpGet]
        [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Edit)]
        public JsonResult Get(int moduleId) {
            FiddleViewModel fvm = FiddleDataService.Instance.GetFiddleDTO(moduleId);
            return Json(fvm, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        [DnnModuleAuthorize(AccessLevel=SecurityAccessLevel.Edit)]
        public JsonResult Save(string fiddleJSON)
        {
            var data = FiddleDataService.Instance;

            FiddleViewModel fiddleDTO = fiddleJSON.FromJson<FiddleViewModel>();

            UserInfo user = UserController.GetCurrentUserInfo();
            data.SaveFiddle(new FiddleInfo()
            {
                ModuleId = fiddleDTO.moduleId,
                Html = fiddleDTO.html,
                Css = fiddleDTO.css,
                Javascript = fiddleDTO.script
            });

            if (fiddleDTO.scripts != null)
            {
                foreach (ScriptViewModel script in fiddleDTO.scripts)
                {
                    if (script._destroy)
                    {
                        data.DeleteFiddleScript(script.scriptid);
                    }
                    else
                    {
                        script.scriptid = data.SaveFiddleScript(fiddleDTO.moduleId, user.UserID, new FiddleScriptsInfo()
                        {
                            ScriptId = script.scriptid,
                            Name = script.name,
                            Enabled = script.enabled,
                            CanDelete = script.canDelete,
                            ModuleId = fiddleDTO.moduleId,
                            Order = script.order,
                            Url = script.url
                        });
                    }
                }
            }

            var serverScripts = from FiddleScriptsInfo s in data.ListFiddleScripts(fiddleDTO.moduleId)
                                select s.ScriptId;

            var clientScripts = from ScriptViewModel s in fiddleDTO.scripts
                                select s.scriptid;

            var deleteScripts = serverScripts.Union(clientScripts);
            deleteScripts = serverScripts.Intersect(clientScripts);

            return Json(fiddleDTO);
        }

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Edit)]
        public JsonResult CreateTempPage(string page)
        {
            string tempDir = String.Format("{0}_FiddleTemp", this.PortalSettings.HomeDirectoryMapPath);
            string tempFile = string.Format("{0}\\{1}.html", tempDir, this.ActiveModule.ModuleID);
            try
            {
                if (!Directory.Exists(tempDir))
                {
                    Directory.CreateDirectory(tempDir);
                }

                System.IO.File.WriteAllText(tempFile, page);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
            string fileUrl = String.Format("{0}_FiddleTemp/{1}.html", this.PortalSettings.HomeDirectory, this.ActiveModule.ModuleID).TrimStart('/');
            return Json(new { urlFragment = fileUrl });
        }
    }
}